package com.sdy.interceptor;

import com.sdy.po.Company;
import com.sdy.po.User;
import com.sdy.util.Contact;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录拦截器
 */
@SuppressWarnings("all")
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 在 执行请求 之前运行的方法
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("Login拦截器生效了");
        User user = (User) request.getSession().getAttribute(Contact.LOGIN_KEY);
        System.out.println(request.getRequestURL());
        if (user == null || user.equals("")){
            try {
                response.sendRedirect("/management");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
        Company company = user.getCompany();
        if (company.getId() == 1){
            request.getSession().setAttribute(Contact.IS_MANAGER,true);
            System.out.println(request.getParameter("url"));
            System.out.println("login拦截器中"+"CCI_"+request.getRequestURI()+"_pass :" + request.getSession().getAttribute("CCI_"+request.getRequestURI()+"_pass"));
            if (request.getSession().getAttribute("CCI_"+request.getRequestURI()+"_pass") == null){
                request.getSession().setAttribute("CCI_"+request.getRequestURI()+"_pass",false);
                System.out.println("login拦截器中"+"CCI_"+request.getRequestURI()+"_pass :" + request.getSession().getAttribute("CCI_"+request.getRequestURI()+"_pass"));
            }
            return true;
        }
        request.getSession().setAttribute("isManager",false);
        request.getSession().setAttribute(Contact.COMPANY_KET,user.getCompany());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("Login拦截器结束了");
    }
}
